<template>
	<view class="container">
		<statusBar></statusBar>
    <!-- 返回栏 -->
		<view class="go-back">
			<view class="left">
				<image src="../../static/close.svg" @click="goBack"/>
				<text>发帖子</text>
			</view>
			<view class="right">
				<text @click="postTopic(0)">存草稿</text>
				<view @click="postTopic(1)">发布</view>
			</view>
		</view>

		<!-- 文本 图片 -->
		<view class="content">
			<uni-easyinput 
				autoHeight 
				type="textarea" 
				:maxlength="200"
				v-model="dataInfo.contentVal" 
				placeholder="添加正文"
			></uni-easyinput>
			<view class="con-upload">
				<cl-upload 
					v-model="fileData.fileList" 
					cloudType="other" 
					:action="fileData.action" 
					:headers="fileData.headers" 
					:listStyle="fileData.listStyle"
					:deleteImg="fileData.deleteImg"
					:data="fileData.data"
					:maxVideo="1"
					:videoFromData="fileData.videoFromData"
					@onSuccess="onSuccess"
				>
					<template #addImg>
						<view class="my-add-img">
							<view>
								<image src="../../static/publish-add.svg" mode="" />
								<text>添加优质</text>
							</view>
							<text>首图更吸引人～</text>
						</view>
					</template>
				</cl-upload>
				
			</view>
			
		</view>

		<!-- 添加标题 话题 -->
		<view class="topic">
			<view class="add-title">
				<view>
					<image src="../../static/publish-title.png" mode="" />
					<text>添加标题</text>
					<uni-easyinput 
						v-model="dataInfo.titleVal" 
						placeholder="请输入标题" 
						:maxlength="30"
						@input="titleInput"
					></uni-easyinput>
				</view>
				
				<text>选填({{dataInfo.titleNum}}/30)</text>
			</view>
			<view class="add-topic">
				<view>
					<image src="../../static/publish-huati.png" mode="" />
					<text>选择话题</text>
					<scroll-view class="topic-list" :scroll-x="true" @scroll="scroll">
						<!-- <text class="item">
							夏天最百搭的背包👜
							<image src="../../static/publish-del.png" mode="" />
						</text> -->
						<view class="item-box">
							<view class="item" v-for="item in dataInfo.changeTopic" :key="item.id">
								{{item.content}}
								<image src="../../static/publish-del.png" mode="" @click="delTopic(item.id)"/>
							</view>
						</view>
						
					</scroll-view>
				</view>
				<image src="../../static/publish-right.png" mode="" @click="toChangeTopic"/>
			</view>
		</view>

		<!-- 去开启定位弹框 -->
		<popupTips ref="popupTipsRef" v-bind="popupTipsValue" @popupTipsOk="popupTipsOk" @popupTipsCancel="popupTipsCancel"></popupTips>

	</view>
</template>
<script setup>
	import { onMounted, ref,reactive } from 'vue'
  import { onShow,onUnload } from "@dcloudio/uni-app";	
	import functions from "@/utils/functions.js";
	import { insertTopic } from '@/api/posting'
	import permision from "@/js_sdk/wa-permission/permission.js"

	const popupTipsRef = ref(null)
	//上传相关
	const fileData = reactive({
		// 样式
		listStyle:{
			columns:3,
			columnGap:'39rpx',
			height:'204rpx'
		},
		deleteImg:'../../static/fashionPurchase/publish-delete.svg',
		// 上传地址
		action: functions.getDomain() + '/zhonggu/user/uploads/singleUploadsFile',
		// action: 'https://gy.ysxdgy.com/v1/common/upload',
		//文件列表
		fileList:[],
		headers: {
			Authorization: 'e8b37ce4-8a23-4877-915f-e9d7016cca89'
		},
		data:{
			type:1
		},
		videoFromData:{
			size:20,
			duration:30
		}
	})

	const dataInfo = reactive({
		titleVal:'',
		contentVal:'',
		titleNum:0, //标题字数
		changeTopic:[] //选中的话题
	})

	const popupTipsValue = reactive({
		content:'开启定位服务即可发布帖子',
		cancel:'再想想', //取消按钮文本
		confirm:'去开启', //确认按钮文本
		isCallback:true //是否按钮需要回调
	})

	onMounted(() => {

	})

	onShow(() => {
		popupTipsRef.value?.close();
		getChangeTopic()
	})

	onUnload(() => {
		// console.log('页面卸载')
		clearChangeTopic()
	})

	const popupTipsOk = () => {
		console.log('确认去开启')
		permision.gotoAppPermissionSetting()
	}

	const popupTipsCancel = () => {
		popupTipsRef.value.close();
	}

	const getChangeTopic = () => {
		dataInfo.changeTopic = uni.getStorageSync('changeTopicList') || [];
		dataInfo.changeTopic = dataInfo.changeTopic.filter(item => item.id)
	}
	const clearChangeTopic = () => {
		uni.setStorageSync('changeTopicList',[])
	}
	const goBack = () => {
		uni.switchTab({
			url: '/pages/index/index'
		});
	}

	const select = (e) => {
		console.log('上传视频',e)
	}

	//上传成功后
	const onSuccess = (reslut) => {
		console.log('上传成功结果',reslut)
		// 把服务端返回的图片地址添加到list中与组件数据同步
		fileData.fileList.push({
			path:reslut.data
		})
	}

	const titleInput = (e) => {
		console.log('e',e,e.length)
		dataInfo.titleNum = e.length
		console.log('dataInfo.titleNum',dataInfo.titleNum)
	}

	const toChangeTopic = () => {
		uni.navigateTo({
			url: '/pages/searchTopic/index'
		});
	}

	//删除话题
	const delTopic = (id) => {
		let newData = dataInfo.changeTopic.filter(item => item.id !== id)
		dataInfo.changeTopic = newData
		uni.setStorageSync('changeTopicList',newData)
		// console.log('newData',newData)
	}

	//发布帖子
	const postTopic = async (status) => {
		if(!dataInfo.contentVal){
			uni.showToast({
				title: '请输入正文',
				duration: 2000,
				icon: 'none'
			});
			return
		}
		if(getFileRegroup().length < 1){
			uni.showToast({
				title: '请至少选择一张图片或一个视频',
				duration: 2000,
				icon: 'none'
			});
			return
		}

		//获取位置信息
	  // console.log('是否打开了权限',permision.checkSystemEnableLocation())	
	  let locationRes = await	appIsLocation()
		console.log('**********************获取到了位置',locationRes)
		

		let datas = {
			content:dataInfo.contentVal,
			banner:getFileRegroup(),
			title:dataInfo.titleVal,
			topicId:getTopicRegroup(),
			ipAddress:locationRes,
			status
		}
		// console.log('datas',datas)
		let res = await insertTopic(datas)
		// console.log('发帖结果',res)
		uni.showToast({
			title: status === 0 ? '已存入草稿箱' : '发布成功',
			duration: 2000,
			icon: 'success'
		});
		setTimeout(() => {
			goBack()
		}, 2000);
	}

	//话题数据重组
	const getTopicRegroup = () => {
		let newList = dataInfo.changeTopic.map(item => {
			return {
				id:item.id,
				content:item.content
			}
		});
		return newList
	}
	//图片视频文件数据重组
	const getFileRegroup = () => {
		let newList = fileData.fileList.map(item => {
			return item.path
		});
		return newList
	}

	//判断当前手机该app是否启用了定位
	const appIsLocation = () => {
	  return new Promise((resolve, reject) => {
			uni.getSystemInfo({
				success: async (res) => {
					// console.log('苹果还是安卓',res.osName)
					let isLocation = false
					if(res.osName == 'ios'){
						isLocation = permision.judgeIosPermission("location")
					}else{
						let result = await permision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
						if (result == 1) {
							isLocation = true
						}else if (result == 0) {
							// strStatus = "未获得授权"
						  return reject('未获得授权')
						} else {
							// strStatus = "被永久拒绝权限"
							isLocation = false
						}
						// console.log('安卓是否授权',strStatus)
						// resolve(strStatus)
					}

					//如果定位被拒绝 需要引导用户去设置页面打开
					if (isLocation) {
						let datas = {
							geocode:true,
						}
						if(res.osName == 'android') datas.type = 'gcj02'
						uni.getLocation({
							...datas,
							success: function (res) {
								// console.log('当前位置' + JSON.stringify(res));
								// console.log('当前位置' + res.address);
								resolve(res.address.province)
							},
							fail: function (err) {
								// console.log('获取位置失败' + JSON.stringify(err));
								reject(err)
							}
						});
					}else{
						popupTipsRef.value.open()
						reject()
					}

				},
				fail: (err) => {
					// console.log('获取权限失败',err)
					reject(err)
				}
			});
		})	
	}



</script>

<style lang='scss' scoped>
	.container{
		width: 100vw;
		height: 100vh;
		background-color: white;

		.go-back{
			width: 750rpx;
			height: 90rpx;
			border-bottom: 2rpx solid #F7F7F7;
			// border-bottom: 2rpx solid #acacac;
			padding: 0 30rpx;
			box-sizing: border-box;
			@include flex(row,space-between);

			.left{
				height: 88rpx;
				@include flex();

				>image{
					width: 40rpx;
					height: 40rpx;
					margin-right: 24rpx;
				}	

				>text{
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 32rpx;
					color: #333333;
				}
			}

			.right{
				@include flex();

				>view{
					width: 104rpx;
					height: 48rpx;
					background: #16DFF2;
					border-radius: 24rpx;
					font-weight: 500;
					font-size: 24rpx;
					color: #FFFFFF;
					line-height: 48rpx;
					text-align: center;
					margin-left: 24rpx;
				}
				text{
					font-weight: 500;
					font-size: 26rpx;
					color: #333333;
				}
			}

		}

		.content{
			width: 690rpx;
			// height: 566rpx;
			background: #FFFFFF;
			border-bottom: 2rpx solid #F7F7F7;
			// border-bottom: 2rpx solid #9b7171;
			margin: 38rpx auto 28rpx auto;
			position: relative;
			padding-bottom: 60rpx;

			::v-deep .uni-easyinput{
				margin-bottom: 50rpx;
			}

			::v-deep .is-input-border{
				border: none;
			}
			::v-deep .uni-easyinput__placeholder-class{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
			}
			textarea{
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
			}

			// ::v-deep .uni-file-picker{
			// 	position: absolute;
			// 	bottom: 10rpx;
			// 	left: 0;
			// }

			// ::v-deep .file-picker__box{
			// 	width: 204rpx !important;
			// 	height: 204rpx !important;
			// 	background: #F4F3F7  !important;
			// 	border: none !important;
			// 	border-radius: 8rpx !important;
			// 	padding-top: 0 !important;
			// }

			// ::v-deep .file-picker__box-content{
			// 	margin: 0 !important;
			// }

			.my-add-img{
				width: 100%;
				height: 100%;
				background-color: #F4F3F7;
				@include flex(column,center,center);

				view{
					@include flex();
					image{
						width: 24rpx;
						height: 24rpx;
					}
					
				}
				text{
					font-weight: 500;
					font-size: 24rpx;
					color: #999999;
				}
				
			}

			.con-upload{
				// position: absolute;
				// bottom: 10rpx;
				// left: 0;
				// background-color: pink;

				::v-deep .uni-group__content {
					padding: 20rpx;
				}
			}
		}

		.topic{
			.add-title,.add-topic{
				width: 690rpx;
				height: 56rpx;
				margin: auto;
				@include flex(row,space-between);

				>view{
					@include flex(row,flex-start);
					>image{
						width: 32rpx;
						height: 32rpx;
						margin-right: 16rpx;
					}
					text{
						font-weight: 400;
						font-size: 28rpx;
						color: #333333;
						margin-right: 30rpx;
					}
				}
				>text{
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;
				}
				>image{
					width: 32rpx;
					height: 32rpx;
				}

				::v-deep .uni-easyinput{
					width: 350rpx !important;
					height: 56rpx;
				}
				
				::v-deep .uni-easyinput__content{
					width: 350rpx !important;
					height: 56rpx;
					background: #F4F3F7 !important;
					border-radius: 28rpx !important;
				}
				::v-deep .is-input-border{
					border: none !important;
				}
				::v-deep .uni-icons{
					color: #DCDCE0 !important;
					font-size: 20px !important;
				}
				input{
					font-weight: 400 !important;
					font-size: 24rpx !important;
					color: #333333 !important;
				}
				
			}

			.add-topic{
				height: 70rpx;
				margin-top: 40rpx;
			}
			.topic-list{
				width: 450rpx;
				height: 56rpx;
				padding-right: 15rpx;
				
				.item-box{
					width: auto;
					display: flex;
					justify-content: flex-start;
        	// flex-wrap: nowrap;
				}
				.item{
					width: auto;
					height: 56rpx;
					line-height: 56rpx;
					padding: 0rpx 60rpx 0 24rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #333333;
					background-color: #F4F3F7;
					border-radius: 28rpx;
					box-sizing: border-box;
					position: relative;
					display: inline-block;
					margin-right: 16rpx;
					flex-shrink: 0;

					>image{
						width: 28rpx;
						height: 28rpx;
						position: absolute;
						top: 14rpx;
						right: 24rpx;
					}
				}

				
			}

		}	

	}
</style>